import RightContent from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { history } from 'umi';
import { notification, message } from 'antd';
import defaultSettings from '../config/defaultSettings';

import { getToken } from '@/utils/index';

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
// export const initialStateConfig = {
//   loading: <PageLoading />,
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
}> {
  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath && !getToken()) {
    history.push(loginPath);
  }
  return {
    // fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      // content: initialState?.currentUser?.name,
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      // // 如果没有登录，重定向到 login
      if (location.pathname !== loginPath && !getToken()) {
        history.push(loginPath);
      }
    },
    links: [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return <>{children}</>;
    },
    ...initialState?.settings,
  };
};

const codeMessage = {
  1003: '用户未登录',
  1004: '请求的参数校验失败',
  1005: '暂无权限',
};
export const request: RequestConfig = {
  errorConfig: {
    adaptor: (resData) => {
      return {
        ...resData,
        success: resData.code === 1000,
      };
    },
  },
  errorHandler: (error: any) => {
    console.log(1, error);
    return {};
  },
  requestInterceptors: [
    (url: string, options: any) => {
      const Authorization = getToken();
      return {
        url,
        options: { ...options, headers: { Authorization }, credentials: 'include' },
      };
    },
  ],
  responseInterceptors: [
    async (response) => {
      const data = await response.clone().json();
      if (response.status >= 400) {
        notification.error({
          message: '系统错误',
          description: JSON.stringify(data),
        });
        throw new Error('系统错误');
      }
      if (codeMessage[data?.code]) {
        message.error(data?.msg);
        throw data;
      }
      return response;
    },
  ],
};
